<?php

class morders_detail extends CI_Model{
    
    private $tbl = "orders_detail";
    
    public function fetchAll(){
        return $this->db->get($this->tbl)->result();
    }
    
    public function fetchOne($id){
        return $this->db->where('id',$id)->get($this->tbl)->row();
    }
    
    public function insert($arr = array()){
        $this->db->insert($this->tbl,$arr);
    }
    
    public function update($id,$arr = array()){
        $this->db->where('id',$id)->update($this->tbl,$arr);
    }
    
    public function delete($id){
        $this->db->delete($this->tbl, array('order_id' => $id)); 
    }
    
    public function deleteAll(){
        $this->db->empty_table($this->tbl); 
    }
    
    public function getByOrderId($id){
        return $this->db->where('order_id',$id)->get($this->tbl)->result();
    }
    
    public function getBestSelling($limit=null){
        if($limit == null) {
            return $this->db->select('*')->select_sum('qty')->group_by("pro_id")->order_by("qty", "desc")->get($this->tbl)->result();
        } else {
            return $this->db->select('*')->select_sum('qty')->group_by("pro_id")->order_by("qty", "desc")->limit($limit)->get($this->tbl)->result();
        }
    }
    
    public function getStatDetail($date){
        $this->db->select('orders_detail.pro_id, orders_detail.name')->select_sum('orders_detail.qty')->from($this->tbl)->join('orders', 'orders_detail.order_id = orders.id');
        $this->db->where('DATE(`orders`.`order_time`)', $date)->group_by('orders_detail.pro_id');
        return $this->db->get()->result();
    }
    
    public function getStatDetailM($date){
        $this->db->select('orders_detail.pro_id, orders_detail.name')->select_sum('orders_detail.qty')->from($this->tbl)->join('orders', 'orders_detail.order_id = orders.id');
        $this->db->where('MONTH(`orders`.`order_time`)', $date)->group_by('orders_detail.pro_id');
        return $this->db->get()->result();
    }
    
}
